{include file="public/header" /}

<style>
   ul>li {
        width:auto !important;

    }
    .ds-default-table ul li {
    color: rgb(51, 51, 51);
    width: 50.1%;
    float: left;
    padding: 4px 0px;
    padding-left: 13px;
}
#brands li {
    color: rgb(51, 51, 51);
    width: 50.1%;
    float: left;
    padding: 4px 0px;
}
</style>
<div class="page">
    <div class="fixed-bar">
        <div class="item-title">
            <div class="subject">
                <h3>新增品牌</h3>
                <h5></h5>
            </div>
            {include file="public/admin_items" /}
        </div>
    </div>
    <div class="fixed-empty"></div>
    <form id="question_class_form" method="post" name="articleClassForm">
        <table class="ds-default-table">
            <tbody id="add_parts">
            <input type="hidden" name="question_id" value="{$model->id | default = 0}">
                <tr >
                    <td colspan="2" ><label class="validation">商品品牌:</label>
                        <div  style='margin-left: 134px;' id="ajax_brand" class="dssc-brand-select w180">
                            <div class="selection">
                            <input style="margin-top:-16px;"  name="b_name" id="b_name" value="{$Request.param.b_name|default=''}" type="text"
                                   class="txt w180" readonly="readonly"/>  
                            <input type="hidden" name="b_id" id="b_id" value="{$Request.param.b_id|default=''}"/>
                    
                        </div>
                            <div style="margin-top: -11px;" class="dssc-brand-select-container">
                                <div class="brand-index" style="width: 210px;padding-bottom: 10px;margin: 6px auto;border-bottom: dotted 1px #CCC;" data-url="{:url('Common/ajax_get_brand')}">
                                    <div class="letter" dstype="letter">
                                        <ul style="width: 100%;" id="brands">
                                            <li style="width: auto;" ><a href="javascript:void(0);" data-letter="all">所有品牌</a></li>
                                            <li style="width: auto;" ><a href="javascript:void(0);" data-letter="A">A</a></li>
                                            <li style="width: auto;" ><a href="javascript:void(0);" data-letter="B">B</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="C">C</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="D">D</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="E">E</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="F">F</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="G">G</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="H">H</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="I">I</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="J">J</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="K">K</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="L">L</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="M">M</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="N">N</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="O">O</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="P">P</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="Q">Q</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="R">R</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="S">S</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="T">T</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="U">U</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="V">V</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="W">W</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="X">X</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="Y">Y</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="Z">Z</a></li>
                                            <li style="width: auto;"><a href="javascript:void(0);" data-letter="0-9">其他</a></li>
                                        </ul>
                                    </div>
                                    <div class="search" dstype="search"><input name="search_brand_keyword" id="search_brand_keyword" type="text" class="text" /><a href="javascript:void(0);" class="dssc-btn-mini" style="vertical-align: top;">Go</a></div>
                                </div>
                                <div class="brand-list" dstype="brandList">
                                    <ul dstype="brand_list">
                                        
                                        {notempty name="brand_list_new"}
                                        {foreach name="brand_list_new" item="val"}
                                        <li data-id='{$val.brand_id}'data-name='{$val.brand_name}'><em>{$val.brand_initial}</em>{$val.brand_name}</li>
                                        {/foreach}
                                        {/notempty}
                                    </ul>
                                </div>
                                <div class="no-result" dstype="noBrandList" style="display: none;">暂无品牌信息</div>
                            </div>
                        </div>
                       

                    </td>
            </tr>
            <tr class="control_after">
                <td>
                    已选择品牌
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td colspan="2" class="required"><label class="validation">问题管理:</label>
                     <div id="gcategory" style="margin-left: 134px;margin-top:-20px;width: 447px;">
                        <select id="new_question" name='question'>
                            <option value="0">请选择</option>
                            {foreach name="question" item="gc"}
                            <option value="{$gc.id}">{$gc.title}</option>
                            {/foreach}
                        </select>
                     </div>
                </td>
            </tr>


            <!-- 规格 -->
             <?php if(is_array($spec_list) && !empty($spec_list)){?>
             <?php $i = '0';?>
             <?php foreach ($spec_list as $k=>$val){?>
             <tr ds_type="spec_group_dl_{$i}" dstype="spec_group_dl" class="spec-bg" {if $k == '1'}spec_img="t"{/if}>

                <td style="width: 102px">
                  <input name="sp_name[{$k}]" type="text" class="text w60 tip2 tr" title="{$Think.lang.specifications_instructions2}" value="<?php if (isset($goods['spec_name'][$k])) { echo $goods['spec_name'][$k];} else {echo $val['sp_name'];}?>" maxlength="10" dstype="spec_name" data-param="{id:<?php echo $k;?>,name:'<?php echo $val['sp_name'];?>'}"/>
                  {$Think.lang.ds_colon}
                </td>

                <td {if $k == '1'}dstype="sp_group_val"{/if}>
                  <ul class="spec" style="margin-left: 5px;">
                        
                        <li data-param="{gc_id:{$goods_class.gc_id},sp_id:{$k},url:'{:url('Nquipment/ajax_add_spec')}'}">

                          <div dstype="specAdd1">
                            <a href="javascript:void(0);" class="dssc-btn" dstype="specAdd"><i class="iconfont">&#xe6db;</i>
                            {if condition="($i == 1)"}添加型号
                            {elseif condition="($i == 0)"}添加规格
                            {/if}
                            </a>
                           </div>

                          <div dstype="specAdd2" style="display:none;">
                            <input class="text w60" type="text" maxlength="20">
                            <a style="margin-left: 21px;" href="javascript:void(0);" dstype="specAddSubmit" class="dssc-btn dssc-btn-acidblue ml5 mr5">{$Think.lang.ds_ok}</a>
                            <a style="margin-left: 10px;" href="javascript:void(0);" dstype="specAddCancel" class="dssc-btn dssc-btn-orange">{$Think.lang.ds_cancel}</a>
                           </div>
                        </li>
                  </ul>
                      <?php if(isset($edit_goods_sign) && $k == '1'){?>
                      <p class="hint">{$Think.lang.specifications_instructions3}</p>
                      <?php }?>
                </td>
             </tr>

             <?php $i++;?>
             <?php }?>
             <?php }?>
             <!-- dl -->
             <tr ds_type="spec_dl" class="spec-bg" style="display:none; overflow: visible;"> 
                <!-- dd -->
                <td class="spec-dd">
            <table style="width: 220px;" border="0" cellpadding="0" cellspacing="0" class="spec_table">
            <thead>
              <label class="validation">规格值管理:</label>
              {notempty name="spec_list"}
              <?php $spec_i=0; ?>
              {foreach name="spec_list" item="val" key="k" }
            <th dstype="spec_name_{$k}" data-type="spec_name_<?php echo $spec_i; ?>" style="display:none"><?php if (isset($goods['spec_name'][$k])) { echo $goods['spec_name'][$k];} else {echo $val['sp_name'];}?></th>
              <?php $spec_i++; ?>
                {/foreach}
              {/notempty}

              <th class="w90">操作
                        <div class="batch"><!-- <i class="iconfont" title="{$Think.lang.batch_operation}">&#xe731;</i> -->
                          <div class="batch-input" style="display:none;">
                            <h6>{$Think.lang.batch_setting_price}：</h6>
                            <a href="javascript:void(0)" class="close">X</a>
                           <!--  <input name="" type="text" class="text price" /> -->
                            <a href="javascript:void(0)" class="dssc-btn-mini" data-type="marketprice">{$Think.lang.set}</a><span class="arrow"></span></div>
                        </div>
            </th>

                </thead>

            <tbody ds_type="spec_table">
            </tbody>
            </table>
                </td>
             </tr>
            <!-- <tr>
                <td colspan="2" class="required"><label>规格:</label>
                <input type="text" value="" name="specifications" id="specifications"  style="width: 200px; margin-left: 99px;" class="txt"><span></span></td>
                 <td class="vatop tips"></td>
            </tr>
            <tr>
                <td colspan="2" class="required"><label>型号:</label>
                <input type="text" value="" name="type_model" id="type_model" style="width: 200px; margin-left: 99px;" class="txt"><span></span></td>
                 <td class="vatop tips"></td>
            </tr> -->
            <tr>
                <td colspan="2" class="required"><label>安装工时:</label>
                <input type="text" value="" name="installation_hours" id='installation_hours' style="width: 200px; margin-left: 73px;" class="txt"><span></span></td>
                 <td class="vatop tips"></td>
            </tr>
            <tr>
                <td colspan="2" class="required"><label>拆移工时:</label>
                <input type="text" value="" name="dismantling_hours" id='dismantling_hours' style="width: 200px; margin-left: 73px;" class="txt"><span></span></td>
                 <td class="vatop tips"></td>
            </tr>
            <tr>
                <td colspan="2" class="required" id="parts2"><label>环境配置:</label>
                    <input type="hidden" name="science" id="science-hidden" value="{$model->id | default = ''}">
                    <textarea value=""  name="science" id="science" style="margin-left: 73px;width: 200px;height: 100px;}"></textarea>
                    <button id="add-science" type="button" class="btn btn-small layui-btn-danger" style="margin-top: 35px;margin-left: 24px;">新增</button>
                </td>
                <td class="vatop tips"></td>
            </tr>
            
            <tr>
                <td  colspan="2" class="required"><label>部位:</label>
                
                    <input type="text" rows="4" id="option" class="txt" style="width: 75px;margin-left: 95px;">
                    <input type="hidden" name="option" id="option-hidden" value="{$model->option_id | default = ''}">
                    
                    <label>保养工时:</label>
                    <input type="text" rows="4" id="an_option" class="txt" style="width: 50px;">
                    <input type="hidden" name="an_option" id="an_option-hidden" value="{$model->option_id | default = ''}">

                    <label>维修工时:</label>
                    <input type="text" rows="4" id="wei_option" class="txt" style="width: 50px;">
                    <input type="hidden" name="wei_option" id="wei_option-hidden" value="{$model->option_id | default = ''}">

                    <button id="add-option" type="button" class="btn btn-small layui-btn-danger">新增</button>
                </td>
                <td class="vatop tips"></td>
            </tr>
            

            {notempty name="options"}
            {foreach $options as $key => $val}

            <tr class="noborder option_{$val.id} parent_id_{$val.parent_id}">
                <td class="required"></td>
                <td class="vatop rowform">
                    {for start="0" end="$val.lev" }
                    &nbsp;&nbsp;&nbsp;&nbsp;|__
                    {/for}
                   <span class="thisoption">{$val.content}</span> <button type="button" data-option="{$val.content}" data-id="{$val.id}" class="btn btn-small btn-red layui-btn-danger del-option">删除</button>
                    <button type="button" data-option="{$val.content}" onclick="updateOption($(this))" data-id="{$val.id}" class="btn btn-small layui-btn-danger">修改</button>
                 
                    <input type="hidden" name="option_answer[{$val.id}]" id="option_answer_{$val.id}" value="{$val.answer_id}">
                    <input type="hidden" name="option_answer_del[]" id="option_answer_del_{$val.id}">
                </td>
                <td class="vatop tips"></td>
            </tr>

            {foreach $val->answers as $k => $v}
            <tr class="noborder answer_{$v.id} option_{$val.id} parent_id_{$val.parent_id}" ischild="1">
                <td class="required"></td>
                <td class="vatop rowform">
                    {for start="0" end="$val.lev" }
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;--
                    {/for}
                    <span class="ss content-text-{$v.id} zy">{$v->content}</span>&nbsp;&nbsp;<button type="button" data-content="{$v.content}" data-option-id="{$val.id}" data-id="{$v.id}" onclick="deleteAnswer($(this))" class="btn btn-small layui-btn-danger">删除</button>
                    <button type="button" data-content="{$v.method}" data-method="{$v.method}" data-id="{$v.id}" onclick="addMethod($(this))" class="btn btn-small">修改</button>
                    <div><br>{for start="0" end="$val.lev" }
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {/for}
                        <span class="mm method-text-{$v.id}">{$v.method}</span>

                    </div>
                </td>
                <td class="vatop tips"></td>
            </tr>
            {/foreach}

            {/foreach}
            {/notempty}

            </tbody>
            <tfoot>
            <tr class="tfoot">
                <td colspan="15" >
                    <input class="btn" id="btn" type="button" value="{$Think.lang.ds_submit}"/>
                </td>
            </tr>
            </tfoot>
        </table>
        <input type="hidden" name="del_all_answer" value="" id="del_all_answer">
        <input type="hidden" name="del_all_option" value="" id="del_all_option">
    </form>
</div>

    <div  class="layui-layer layui-layer-page layui-layer-prompt" id="add-answer-textaret"  style="z-index: 19891018; top: 8%; left: 40%; display: none;">
        <div class="layui-layer-title" style="cursor: move;">原因管理</div>
        <div id="" class="layui-layer-content">
            <div class="layui-layer-title" style="background: white">添加原因:</div>
            <textarea class="layui-layer-input" id="answer-content" style="background: white"></textarea>
            <br>
            <div class="layui-layer-title" style="background: white">添加处理办法:</div>
            <textarea class="layui-layer-input" id="method-content" style="background: white"></textarea>
        </div>
        <span class="layui-layer-setwin">
            <a class="layui-layer-ico layui-layer-close layui-layer-close1" href="javascript:;"></a>
        </span>
        <div class="layui-layer-btn layui-layer-btn-">
            <button class="btn btn-small" style="margin-top:5px;" id="add-answer-zidi" data-that="" data-lev data-id="" data-parent="" onclick="addAnswerPost($(this))">确定</button>
            <button class="btn btn-small" style="display: none;margin-top:5px;" id="edit-answer-zidi" data-that="" data-lev data-id="" onclick="EditAnswerPost($(this))">确定</button>
            <a class="layui-layer-btn1">取消</a>
        </div>
    </div>
    <div id="alert_message" style="display:none">
    <iframe name=iframe_form id="ifr" scrolling="no"></iframe>
</div>
<script src="{$Think.PLUGINS_SITE_ROOT}/js/jquery-file-upload/jquery.fileupload.js"></script>
    <link rel="stylesheet" href="{$Think.PLUGINS_SITE_ROOT}/js/jquery-ui-timepicker/jquery-ui-timepicker-addon.min.css">
<script src="{$Think.PLUGINS_SITE_ROOT}/js/jquery-ui-timepicker/jquery-ui-timepicker-addon.min.js"></script>
<script src="{$Think.PLUGINS_SITE_ROOT}/js/jquery-ui-timepicker/i18n/jquery-ui-timepicker-zh-CN.js"></script>
<script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/mlselection.js" charset="utf-8"></script>
<script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/jquery.mousewheel.js"></script> 

<!-- 规格 -->
        <script src="{$Think.PLUGINS_SITE_ROOT}/jquery.ajaxContent.pack.js"></script>
        <script src="{$Think.PLUGINS_SITE_ROOT}/mlselection.js"></script>
        <script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/js/fileupload/jquery.iframe-transport.js"
                charset="utf-8"></script>
        <script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/js/fileupload/jquery.ui.widget.js"
                charset="utf-8"></script>
        <script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/js/fileupload/jquery.fileupload.js"
                charset="utf-8">
        </script>

        <script src="{$Think.PLUGINS_SITE_ROOT}/jquery.mousewheel.js"></script>

        <script src="{$Think.PLUGINS_SITE_ROOT}/layui/layui.js"></script>

        <script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/jquery.charCount.js"></script>


        <!--[if lt IE 8]>
        <script src="{$Think.BASE_SITE_ROOT}/js/json2.js"></script>
        <![endif]-->
        <script src="{$Think.HOME_SITE_ROOT}/js/sellergoods_add_step2.js"></script>
<!-- end -->
<script>
  //增加一行
  // $("#add-science").click(function() {
  //       var str = '<tr>';
  //           str += '<td colspan="2" class="required"><label style="margin-left: 46px;"></label>';
  //           str += '<input type="text" value="" name="science[]" style="width: 200px; margin-left: 75px;" class="txt"><span></span>';
  //           str += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  //           str += '<button id="add-science" type="button" class=" btn btn-small layui-btn-danger shanchu" style="background-color: #FF5722;">删除</button></td>';
  //           str +=  '</tr>';
  //           $("#parts2").append(str);
  //           //删除父级元素
  //       $(".shanchu").click(function() {
  //           $(this).parent().parent().remove();
  //       });
  //  });


    //按钮先执行验证再提交表单
$(document).ready(function(){
    /* AJAX选择品牌 */
    $("#ajax_brand").brandinit();

    $('#dssubmit').click(function(){
        $('#formSearch').submit();
    });
    $('#dssubmit').click(function(){
        $('#formSearch').submit();
    });
    $('#company_address').ds_region();
    $('ul[dstype="brand_list"]').prop("onclick","null").off("click");
        // 选择品牌
        $('ul[dstype="brand_list"]').on('click', 'li', function () {

        if($('#b_id').val().indexOf($(this).attr('data-id')+",") >=0){
            if($('#b_id').val()!=''){
                $('.dssc-brand-select > .dssc-brand-select-container').hide();
                return ;
            }
       
        }
 

        $('#b_id').val( $('#b_id').val() +  $(this).attr('data-id')+",");
        $('#b_name').val($('#b_name').val()  + $(this).attr('data-name') +",");
     
                var str = '<div  class = "control_list" style=" float: left; display: inline-block; margin-left:15px;>'; 
                    str += '<span class="thisoption"  >'+$(this).attr('data-name')+'</span>';
                    str += '<button type="button" style="margin-left: 10px;" class=" btn btn-small layui-btn-danger shanchu" style="background-color: #FF5722;" data-nid="'+$(this).attr('data-id')+'" data-name="' + $(this).attr('data-name')  +  '" >删除</button>';
                    str += '</div>';
                    $('.control_after td:eq(1)').append(str);
                    
        $('.dssc-brand-select > .dssc-brand-select-container').hide();
    });

    $('.control_after').on('click', '.control_list button', function () {
          $('#b_id').val( $('#b_id').val().replace($(this).data("nid")+",",""));
          $('#b_name').val($('#b_name').val().replace($(this).data("name")+",","")); 
          $(this).parent().remove();
    });

    });
    


// 规格:
            // 按规格存储规格值数据
            var spec_group_checked = new Array();
            <?php for($i=0; $i<$sign_i; $i++){ ?>
                spec_group_checked["<?php echo $i;?>"]='';
            <?php } ?>
            var str = '';
            var V = new Array();

            <?php for ($i=0; $i<$sign_i; $i++){?>
                var spec_group_checked_<?php echo $i;?> = new Array();
            <?php }?>

            $(function(){
                $('tr[dstype="spec_group_dl"]').on('click', 'span[dstype="input_checkbox"] > input[type="checkbox"]',function(){
                    into_array();
                    goods_stock_set();
                });

                // 提交后不没有填写的价格或库存的库存配置设为默认价格和0
                // 库存配置隐藏式 里面的input加上disable属性
                $('input[type="submit"]').click(function(){
                    $('input[data_type="price"]').each(function(){
                        if($(this).val() == ''){
                            $(this).val($('input[name="g_price"]').val());
                        }
                    });
                    $('input[data_type="stock"]').each(function(){
                        if($(this).val() == ''){
                            $(this).val('0');
                        }
                    });
                    $('input[data_type="alarm"]').each(function(){
                        if($(this).val() == ''){
                            $(this).val('0');
                        }
                    });
                    if($('tr[ds_type="spec_dl"]').css('display') == 'none'){
                        $('tr[ds_type="spec_dl"]').find('input').prop('disabled','disabled');
                    }
                });

            });
            // 将选中的规格放入数组
            function into_array(){
            <?php for ($i=0; $i<$sign_i; $i++){?>

                    spec_group_checked_<?php echo $i;?> = new Array();
                    $('tr[ds_type="spec_group_dl_<?php echo $i;?>"]').find('input[type="checkbox"]:checked').each(function(){
                        i = $(this).attr('ds_type');
                        v = $(this).val();
                        c = null;
                        if ($(this).parents('tr:first').attr('spec_img') == 't') {
                            c = 1;
                        }
                        spec_group_checked_<?php echo $i;?>[spec_group_checked_<?php echo $i;?>.length] = [v,i,c];
                    });

                    spec_group_checked["<?php echo $i;?>"] = spec_group_checked_<?php echo $i;?>;

                <?php }?>
            }

            // 生成库存配置
            function goods_stock_set(){
                //  店铺价格 商品库存改为只读
                $('input[name="g_price"]').attr('readonly','readonly').css('background','#E7E7E7 none');
                $('input[name="g_storage"]').attr('readonly','readonly').css('background','#E7E7E7 none');

                $('tr[ds_type="spec_dl"]').show();
                str = '<tr>';
            <?php recursionSpec(0,$sign_i);?>
                //生成字符串开始
                {notempty name="spec_list"}
                {foreach name="spec_list" item="val" key="k" }
                $('[data-type=spec_name_'+({$k})+']').hide();
                {/foreach}
                    {/notempty}
                        var total_length=0;
                        for(var i in checked_group){
                            $('[data-type=spec_name_'+(i)+']').show();
                            if(total_length==0){
                                total_length=1;
                            }
                            total_length=total_length*spec_group_checked[checked_group[i]].length;
                        }

                        var k=new Array();
                        var l=0;
                        var n=0;
                        for(var j=0;j<total_length;j++){
                            var spec_bunch='i_';
                            var sub_str='';
                            sub_str += '<input type="hidden" name="spec[spec_bunch]" ds_type="spec_bunch|id" value="" />';
                            for(var i in checked_group){


                                if(typeof(k[checked_group[i]])=='undefined'){
                                    k[checked_group[i]]=0;
                                }
                                spec_bunch+=spec_group_checked[checked_group[i]][k[checked_group[i]]][1];
                                if (spec_group_checked[checked_group[i]][k[checked_group[i]]][2] != null) { sub_str += '<input type="hidden" name="spec[spec_bunch][color]" value="'+spec_group_checked[checked_group[i]][k[checked_group[i]]][1]+'" />';}
                                sub_str +='<td><input type="hidden" name="spec[spec_bunch][sp_value]['+spec_group_checked[checked_group[i]][k[checked_group[i]]][1]+']" value="'+spec_group_checked[checked_group[i]][k[checked_group[i]]][0]+'" />'+spec_group_checked[checked_group[i]][k[checked_group[i]]][0]+'</td>';
                                //checked_group存储选中的规格的键
                                //spec_group_checked存储选中的规格的值
                                //k表示规格值的指针
                                //total_length表示选中规格的总长度

                                //由最后一个规格开始遍历，如果满了，则前面的规格指针增加，同时当前指针指置0

                                //最后一个规格项
                                //最后规格的指针增加
                                //最后一个规格的指针满了
                                //从最后的规格开始向前遍历
                                //如果规格指针没有满
                                //规格指针增加
                                //规格指针复位
                                if(i==(checked_group.length-1)){
                                    k[checked_group[i]]++;
                                    if(k[checked_group[i]]==spec_group_checked[checked_group[i]].length){
                                        for(var m = (checked_group.length-1);m>=0;m--){
                                            if(k[checked_group[m]]<(spec_group_checked[checked_group[m]].length-1)){
                                                k[checked_group[m]]++;
                                                break;
                                            }else{
                                                k[checked_group[m]]=0;
                                            }
                                        }
                                    }
                                }
                            }

                            sub_str +='<td><button type="button" onclick="delete2($(this))"  class="btn btn-small layui-btn-danger">删除</button></td></tr>';
                            sub_str=sub_str.replace(/spec_bunch/g, spec_bunch);
                            str +=sub_str;
                        }
                        //生成字符串结束

                        if(str == '<tr>'){
                            
                            //  店铺价格 商品库存取消只读
                            $('input[name="g_price"]').removeAttr('readonly').css('background','');
                            $('input[name="g_storage"]').removeAttr('readonly').css('background','');
                            $('tr[ds_type="spec_dl"]').hide();
                        }else{

                            $('tbody[ds_type="spec_table"]').empty().html(str)
                                .find('input[ds_type]').each(function(){

                                s = $(this).attr('ds_type');

                                try{$(this).val(V[s]);}catch(ex){$(this).val('');};

                                if ($(this).attr('data_type') == 'marketprice' && $(this).val() == '') {
                                    $(this).val($('input[name="g_marketprice"]').val());
                                }

                                if ($(this).attr('data_type') == 'price' && $(this).val() == ''){
                                    $(this).val($('input[name="g_price"]').val());
                                }

                                if ($(this).attr('data_type') == 'stock' && $(this).val() == ''){
                                    $(this).val('0');
                                }

                                if ($(this).attr('data_type') == 'alarm' && $(this).val() == ''){
                                    $(this).val('0');
                                }

                            }).end()
                                .find('input[data_type="stock"]').change(function(){
                                computeStock();    // 库存计算
                            }).end()
                                .find('input[data_type="price"]').change(function(){
                                computePrice();     // 价格计算
                            }).end()
                                .find('input[ds_type]').change(function(){
                                s = $(this).attr('ds_type');
                                V[s] = $(this).val();
                            });
                        }
                    }

                <?php
                    /**
                     *
                     *
                     *  生成需要的js循环。递归调用  PHP
                     *
                     *  形式参考 （ 2个规格）
                     *  $('input[type="checkbox"]').click(function(){
                     *      str = '';
                     *      for (var i=0; i<spec_group_checked[0].length; i++ ){
                     *      td_1 = spec_group_checked[0][i];
                     *          for (var j=0; j<spec_group_checked[1].length; j++){
                     *              td_2 = spec_group_checked[1][j];
                     *              str += '<tr><td>'+td_1[0]+'</td><td>'+td_2[0]+'</td><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td>';
                     *          }
                     *      }
                     *      $('table[class="spec_table"] > tbody').empty().html(str);
                     *  });
                     */
                    function recursionSpec($len,$sign) {
                        echo "var checked_group=new Array();\n";
                        for($i=0; $i< $sign; $i++){
                            echo "if(spec_group_checked['".$i."'].length>0){ checked_group.push('".$i."'); }\n";
                        }


                    }
                        ?>


 // TODO  隐藏规格
function hide(obj){  
    $(obj).parent().parent().hide();  
}  
// TODO  删除规格
function delete2(obj){
    $(obj).parent().parent().parent()[0].removeChild($(obj).parent().parent()[0]);
}

                <?php if (!empty($goods) && !empty($sp_value) && !empty($spec_checked) && !empty($spec_list)){?>

//  编辑商品时处理JS
                    $(function(){
                        var E_SP = new Array();
                        var E_SPV = new Array();
                        {php}
                        $string = '';
                        foreach ($spec_checked as $v) {
                            $string .= "E_SP[".$v['id']."] = '".$v['name']."';";
                        }
                        echo $string;
                        echo "\n";
                        $string = '';
                        foreach ($sp_value as $k=>$v) {
                            $string .= "E_SPV['".$k."'] = '".$v."';";
                        }
                        echo $string;
                        {/php}
                            V = E_SPV;
                            $('tr[ds_type="spec_dl"]').show();
                            $('tr[dstype="spec_group_dl"]').find('input[type="checkbox"]').each(function(){

                                //  店铺价格 商品库存改为只读
                                $('input[name="g_price"]').attr('readonly','readonly').css('background','#E7E7E7 none');
                                $('input[name="g_storage"]').attr('readonly','readonly').css('background','#E7E7E7 none');
                                s = $(this).attr('ds_type');
                                if (!(typeof(E_SP[s]) == 'undefined')){
                                    $(this).prop('checked',true);
                                    v = $(this).parents('li').find('span[dstype="pv_name"]');
                                    if(E_SP[s] != ''){
                                        $(this).val(E_SP[s]);
                                        v.html('<input type="text" maxlength="20" value="'+E_SP[s]+'" />');
                                    }else{
                                        v.html('<input type="text" maxlength="20" value="'+v.html()+'" />');
                                    }
                                    change_img_name($(this));     // 修改相关的颜色名称
                                }
                            });

                            into_array(); // 将选中的规格放入数组
                            str = '<tr>';
                        <?php recursionSpec(0,$sign_i);?>

                            //生成字符串开始

                            var total_length=0;
                            for(var i in checked_group){
                                $('[data-type=spec_name_'+(i)+']').show();
                                if(total_length==0){
                                    total_length=1;
                                }
                                total_length=total_length*spec_group_checked[checked_group[i]].length;
                            }

                            var k=new Array();
                            var l=0;
                            var n=0;
                            for(var j=0;j<total_length;j++){
                                var spec_bunch='i_';
                                var sub_str='';
                                sub_str += '<input type="hidden" name="spec[spec_bunch]" ds_type="spec_bunch|id" value="" />';
                                for(var i in checked_group){


                                    if(typeof(k[checked_group[i]])=='undefined'){
                                        k[checked_group[i]]=0;
                                    }
                                    spec_bunch+=spec_group_checked[checked_group[i]][k[checked_group[i]]][1];
                                    if (spec_group_checked[checked_group[i]][k[checked_group[i]]][2] != null) { sub_str += '<input type="hidden" name="spec[spec_bunch][color]" value="'+spec_group_checked[checked_group[i]][k[checked_group[i]]][1]+'" />';}
                                    sub_str +='<td><input type="hidden" name="spec[spec_bunch][sp_value]['+spec_group_checked[checked_group[i]][k[checked_group[i]]][1]+']" value="'+spec_group_checked[checked_group[i]][k[checked_group[i]]][0]+'" />'+spec_group_checked[checked_group[i]][k[checked_group[i]]][0]+'</td>';

                                    if(i==(checked_group.length-1)){
                                        k[checked_group[i]]++;
                                        if(k[checked_group[i]]==spec_group_checked[checked_group[i]].length){
                                            for(var m = (checked_group.length-1);m>=0;m--){
                                                if(k[checked_group[m]]<(spec_group_checked[checked_group[m]].length-1)){
                                                    k[checked_group[m]]++;
                                                    break;
                                                }else{
                                                    k[checked_group[m]]=0;
                                                }
                                            }
                                        }
                                    }
                                }

                                sub_str +='<td><input class="text price" type="text" name="spec[spec_bunch][marketprice]" data_type="marketprice" ds_type="spec_bunch|marketprice" value="" /><em class="add-on"><i class="iconfont">&#xe65c;</i></em></td></tr>';
                                sub_str=sub_str.replace(/spec_bunch/g, spec_bunch);
                                str +=sub_str;
                            }
                            //生成字符串结束


                            if(str == '<tr>'){
                                $('tr[ds_type="spec_dl"]').hide();
                                $('input[name="g_price"]').removeAttr('readonly').css('background','');
                                $('input[name="g_storage"]').removeAttr('readonly').css('background','');
                            }else{
                                $('tbody[ds_type="spec_table"]').empty().html(str)
                                    .find('input[ds_type]').each(function(){
                                    s = $(this).attr('ds_type');
                                    try{$(this).val(E_SPV[s]);}catch(ex){$(this).val('');};
                                }).end()
                                    .find('input[data_type="stock"]').change(function(){
                                    computeStock();    // 库存计算
                                }).end()
                                    .find('input[data_type="price"]').change(function(){
                                    computePrice();     // 价格计算
                                }).end()
                                    .find('input[type="text"]').change(function(){
                                    s = $(this).attr('ds_type');
                                    V[s] = $(this).val();
                                });
                            }
                        });
                <?php }?>


// 规格end
              $(function() {
                   // 类型搜索
             $(document).off('change',"#gcategory > select").on("change","#gcategory > select", function() {
                      type_scroll($(this));
                  });
               var typeScroll = 0;
              function type_scroll(o) {
                  var id = o.val();
                  if (!$('#type_dt_' + id).is('dt')) {
                      return false;
                  }
                  $('#type_div').scrollTop(-typeScroll);
                  var sp_top = $('#type_dt_' + id).offset().top;
                  var div_top = $('#type_div').offset().top;
                  $('#type_div').scrollTop(sp_top - div_top);
                  typeScroll = sp_top - div_top;
              }
              gcategoryInit('gcategory');


                    $('#area_id1').change(function() {
                    var htmls ='<option value="0">请选择...</option>';
                     $('#area_id2').html(htmls);
                     $('#area_id3').html(htmls);
                    var area_id =$(this).val();
                      if (area_id == '0') {
                        var htmls ='<option value="0">请选择...</option>';
                         $('#area_id2').html(htmls);
                         $('#area_id3').html(htmls);
                      } else {
                           $.ajax({
                          //请求方式
                          type : "POST",
                          //请求地址
                          url : "ajax_get_area_class",
                          //数据，json字符串
                          data : {'area_id':area_id},
                          //请求成功
                          success : function(result) {
                             var htmls ='<option value="0">请选择...</option>';
                             $.each(result,function(item,v){
                                htmls+="<option value='"+v.area_id+"'>"+v.area_name+"</option>";
                             });

                         $('#area_id2').html(htmls);
                          },
                          //请求失败，包含具体的错误信息
                          error : function(e){
                              console.log(e.status);
                              console.log(e.responseText);
                          }
                      });
                      }
                  });

                    $('#area_id2').change(function() {
                    var htmls ='<option value="0">请选择...</option>';
                    var area_id =$(this).val();

                    $('#area_id3').html(htmls);
                      if (area_id == '0') {

                       /*  $('#gc_id2').html(htmls);*/
                         $('#area_id3').html(htmls);
                      } else {
                           $.ajax({
                          //请求方式
                          type : "POST",
                          //请求地址
                          url : "ajax_get_area_class",
                          //数据，json字符串
                          data : {'area_id':area_id},
                          //请求成功
                          success : function(result) {
                             var htmls ='<option value="0">请选择...</option>';
                             $.each(result,function(item,v){
                                htmls+="<option value='"+v.area_id+"'>"+v.area_name+"</option>";
                             });

                         $('#area_id3').html(htmls);
                          },
                          //请求失败，包含具体的错误信息
                          error : function(e){
                              console.log(e.status);
                              console.log(e.responseText);
                          }
                      });
                      }
                  });
              });

    function confirm(){
        var _area_3 = $('#_area_3').val();
        var class_id = $('#class_id').val();
        var lastId = $('#upload_img').parent().next().find('span').last().attr('data_id');

        if(_area_3==''){
            layer.msg('请选择所在地');return false;
        }
        if(class_id=='0'){
            layer.msg('请选择分类');return false;
        }
        if(lastId=='-1'){
            layer.msg('请上传图片');return false;
        }
        var res =  $('form').valid();
            if(res){
                var url = $('form').attr('action');
                //alert(url);return false;
                // alert(url);return false;
                $.ajax({
                    type: "POST",
                    url:url,
                    data:$('#add_form').serialize(),// 你的formid

                    error: function(request) {
                        alert("Connection error");
                    },
                    success: function(data) {
                        if(data.code==0){

                            layer.msg(data.msg);
                            location.href=data.url;return false;
                        }else{
                            layer.msg(data.msg);
                            location.href=data.url;return false;

                        }
                    }
                }); return false;
            }else{
                layer.msg('操作失败');return false;
            }
    }

    //旧的
    function ischild() {
        $('.add-answer').each(function () {
            var ischild = $(this).parent().parent().next().attr('ischild');
            if (ischild) {
                $(this).css('background', '#ccc');
                $(this).attr('disabled', true)
            } else {
                $(this).css('background', '');
                $(this).removeAttr('disabled')
            }
        })
        $('button').each(function () {
            if ($(this).text() == '添加原因') {
                var ischild = $(this).parent().parent().next().attr('ischild');
                if (ischild) {
                    $(this).css('background', '#ccc');
                    $(this).attr('disabled', true)
                }else {
                    $(this).css('background', '');
                    $(this).removeAttr('disabled')
                }
            }

        })
    }
    ischild()

    $('#btn').click(function () {
        var b_id = $('#b_id').val();
        if(b_id == 0){
            layer.msg('请选择品牌');
            return false;
        }
        var question = $('#new_question').val();
        if(question == 0){
            layer.msg('请选择绑定的问题');
            return false;
        }
        if (!$('#installation_hours').val()) {
            layer.msg('安装工时不能为空');
            return false;
        }
        $('#question_class_form').submit();
    })
    $('#title').blur(function () {
        if ($(this).attr('is_add') == 0) {
            return false;
        }
        if (!$(this).val()) {
            layer.msg('请输入问题名称')
            return false;
        }
        $.post('uniqueQuestion', {
            title: $(this).val()
        }, function (res) {
            if (res.code == 10000) {
                layer.msg(res.message);
                $(this).text('')
                $(this).val('')
                $('#btn').css('background', '#ccc');
                $('#btn').attr('disabled', 'true');
            } else {
                $('#btn').css('background', '');
                $('#btn').removeAttr('disabled');
            }
        }, 'json')
    })
    function EditAnswerPost(that) {
        var id = that.attr('data-id');
        var pass= $('#answer-content').val()
        var method = $('#method-content').val()
        if (!pass) {
            layer.msg('原因不能为空');
            return false;
        }
        if (!method) {
            layer.msg('处理方法不能为空');
            return false;
        }
        $.post('addMethod.html?id='+id, {
            content: pass,
            method: method
        }, function (res) {
            console.log(res)
            layer.msg(res.message)
            if (res.code == 10000) {
                console.log(213123);
                $('.content-text-'+id).text(res.data.content)
                $('.method-text-'+id).text(res.data.method)
            }
        layer.closeAll()
        }, 'json')
    }
    // TODO 添加或修改处理方法
    function addMethod(that) {
        $('#add-answer-zidi').hide();
        $('#edit-answer-zidi').show();
        var id = that.attr('data-id');
        var content = $('.content-text-'+id).text();
        var method = $('.method-text-'+id).text();

        $('#answer-content').val($('.content-text-'+id).text());
        $('#method-content').val(method)
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            offset: ['8%', '40%'],
            content: $('#add-answer-textaret')
        });
        $('#edit-answer-zidi').attr('data-id', id)
        $('#edit-answer-zidi').attr('data-that', $('#edit-answer-'+id))
    }
    // TODO 修改选项
    function updateOption(that) {
        var id = that.attr('data-id');
        var content = that.attr('data-option');
        var index = layer.prompt({title: '修改-'+content, formType: 2, value: content}, function(pass, index){
            layer.close(index);
            $.post('updateOption.html?id='+id, {
                content: pass
            }, function (res) {
                layer.msg(res.message);
                if (res.code == 10000) {
                    that.parent().children().eq(0).text(pass)
                }
            }, 'json')
            // layer.msg('添加选项“'+pass+'"成功')
        });
    }
    // TODO 点击新增下级
    function addChild(that) {
        var parentid = that.attr('data-id'); // 父级的id
        var lev = that.attr('data-lev'); // 父级的级别
        layer.prompt({title: '请输入次级现象', formType: 2}, function(pass, index){
            layer.close(index);;
            addOption(pass, parentid, parseInt(lev)+1)
            // layer.msg('添加选项“'+pass+'"成功')
        });
    }

    // TODO 增加答案
    function addAnswer(that) {
        $('#answer-content').val('');
        $('#method-content').val('');
        var parentid = that.attr('data-parentid')
        var id = that.attr('data-id');
        var lev = that.attr('data-lev')
        console.log(id);
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            offset: ['8%', '40%'],
            content: $('#add-answer-textaret')
        });
        $('#add-answer-zidi').show();
        $('#edit-answer-zidi').hide();
        $('#add-answer-zidi').attr('data-id', id)
        $('#add-answer-zidi').attr('data-lev', lev)
        $('#add-answer-zidi').attr('data-that', $('#add-answer-'+id))
        $('#add-answer-zidi').attr('data-parentid', parentid)
    }
    var isclose = false;
    function addAnswerPost(that)
    {

        var id = that.attr('data-id');
        var lev = that.attr('data-lev')
        var pass = $('#answer-content').val();
        var method = $('#method-content').val();
        var thoese = $('add-answer-'+id);
        var parentid = that.attr('data-parentid');
        if (!pass) {
            layer.msg('原因不能为空');
            return false;
        }
        if (!method) {
            layer.msg('处理方法不能为空');
            return false;
        }
        console.log('----');
        console.log(id)
        var rfalse = false;
        $('.ss').each(function () {
            console.log($(this).text())
            if ($(this).text() == pass) {
                rfalse = true;
                layer.msg('该原因已存在');
                return false;
            }
        })
        $('.mm').each(function () {
            console.log($(this).text())
            if ($(this).text() == method) {
                rfalse = true;
                layer.msg('该处理办法已存在');
                return false;
            }
        })
        if (rfalse) {
            layer.msg('该原因已存在')
            return false;
        }
        if (isclose) {
            layer.msg('点击过快，请稍后。。')
            return false;
        }
        isclose = true;
        $.post('addOptionAnswer?option_id='+id, {
            content: pass,
            method: method,
            delmethodid: $('#del_all_answer').val()
        }, function (res) {
            if (res.code != 10000) {
                layer.msg(res.message, {time:500}, function () {
                    // layer.closeAll()
                    isclose = false
                })
                return false;
            }
            var pas = '';
            for (i=0; i<lev; i++) {
                pas += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
            }
            pas += '--';
            console.log(res.data.id)
            var html = '<tr class="noborder answer_'+res.data.id+' option_'+id+' parent_id_'+parentid+'" ischild="1">\n' +
                '<td class="required"></td>'+
                '<td class="vatop rowform">\n' +
                '    '+pas+'<span class="ss content-text-'+res.data.id+' zy">'+pass+'</span> <button type="button" data-content="'+pass+'" data-option-id="'+id+'" data-id="'+res.data.id+'" onclick="deleteAnswer($(this))" class="btn btn-small layui-btn-danger">删除</button>\n' +
                '&nbsp;<button type="button" data-content="'+pass+'" data-method="'+res.data.method+'" data-id="'+res.data.id+'" onclick="addMethod($(this))" class="btn btn-small">修改</button>'+
                '<div><br>' +
                '   '+pas+'<span class="mm method-text-'+res.data.id+'">'+res.data.method+'</span>\n' +
                '\n' +
                '                    </div>'
                '</td>\n' +
                '</tr>';
            // console.log(html)
            $('#add-answer-'+id).parent().parent().after(html);
            var answer_ids = $('#option_answer_'+id).val();
            console.log(answer_ids);
            console.log('#option_answer_'+id);
            console.log(answer_ids+','+res.data.id);
            if (!answer_ids) {
                $('#add-answer-'+id).next().val(res.data.id);
            } else {
                $('#add-answer-'+id).next().val(answer_ids+','+res.data.id);
            }
            $('#add-answer-'+id).attr('disabled' , true)
            $('#add-answer-'+id).css('background', '#ccc');

            that.attr('data-id', '');
            that.attr('data-lev', '')
            $('#answer-content').val('');
            $('#method-content').val('');
            layer.msg(res.message, {time: 1000}, function () {
                layer.closeAll()
                isclose = false
            })

        });
        ischild()
    }

    // TODO 删除答案
    function deleteAnswer(that) {
        var id = that.attr('data-id');
        var option_id = that.attr('data-option-id');
        var index = layer.confirm('确定要删除"'+that.attr('data-content')+'"答案吗？', {
            btn: ['确定', '取消'],
            title: false,
        }, function () {
            $('.answer_'+id).remove();
            ischild()
            var del = $('#option_answer_del_'+option_id).val();
            $('#option_answer_del_'+option_id).val(del+','+id);
            $('#del_all_answer').val(del+','+id);
            var answer_id = $('#option_answer_'+option_id).val();
            if (!answer_id) {
                answer_id = '';
            }
            answer_id = answer_id.split(',');
            for (i in answer_id) {
                if (!answer_id[i]) {
                    answer_id.splice(i, 1); // 删除空元素
                }
                if (answer_id[i] == id) {
                    answer_id.splice(i, 1); // 删除删掉的答案id
                }
            }
            answer_id = answer_id.join(',');
            if (!answer_id) {
                $('#option_answer_'+option_id).prev().removeAttr('disabled')
                $('#option_answer_'+option_id).prev().removeClass('background')
                $('#option_answer_'+option_id).prev().css('background', '')
            }
            $('#option_answer_'+option_id).val(answer_id);
            layer.msg('删除成功', {time: 500}, function () {
                ischild()
                layer.close(index)
            })


        })
        ischild()
    }

    // TODO 新增环境配置
    $('#add-science').click(function () {
        var science = $('#science').val();
        addScience(science,0, 0)
        ischild()
    })

    /**
     *  TODO 环境配置
     * @param option
     * @returns {boolean}
     */
    function addScience(science, parentid, lev) {
        if (!science) {
            layer.msg('文本不能为空');
            return false;
        }
        if (!parentid) parentid = 0;
        if (!lev) lev = 0;
        var isfalse = false;
        $('.thisoption').each(function () {
            if ($(this).text() == option) {
                isfalse = true;
            }
        })
        // if (isfalse) {
        //     layer.msg('已存在该现象');
        //     return false;
        // }
        $.post('addScience?parent_id='+parentid, {
            science: science,
            lev: lev,
            deloption: $('#del_all_option').val()
        }, function (res) {

            console.log(res);
            layer.msg(res.message);
            if (res.code == 10000) {
                var del = $('#del_all_option').val()
                console.log('--+'+del)
                del = del.split(',');
                for (i in del) {
                    if (del[i] == res.data.id) {
                        del.splice(i, 1)
                    }
                }
                del = del.join(',');
                console.log('--'+del)
                $('#del_all_option').val(del)
                var lev_html = '';
                var str = '<tr>';
                    str += '<td colspan="2" class="required"><label style="margin-left: 46px;"></label>';
                    str += '<div style="width:230px;margin-left: 117px;">';
                     str += '<input type="hidden" value="'+res.data.id+'" name="science[]" style="width: 200px; margin-left: 75px;" class="txt"><span></span>';
                    str += '<span class="thisoption" style="width:100px;">'+science+'</span>';
                    str += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    str += '<button type="button" class=" btn btn-small layui-btn-danger shanchu" style="background-color: #FF5722;">删除</button></td>';
                    str += '</div>';
                    str +=  '</tr>';

                if (parentid != 0) {
                    $('.science_'+parentid).after(str);
                } else {
                    $("#parts2").append(str);
                }
                $('#science').val(option);
                $('#science').val('');

                var science_ids = $('#science-hidden').val();
                var science_arr = science_ids.split(',');
                science_arr.push(res.data.id);
                science_ids = science_arr.join(',');
                $('#science-hidden').val(science_ids);

                $(".shanchu").click(function() {
                    $(this).parent().parent().remove();
                });
            }
        }, 'json')
        ischild()
    }

    // TODO 点击添加选项
    $('#add-option').click(function () {
        var option = $('#option').val();
        var an_option = $('#an_option').val();
        var wei_option = $('#wei_option').val();
        addOption(option,an_option,wei_option, 0, 0)
        ischild()
    })

    /**
     *  TODO 添加选项
     * @param option
     * @returns {boolean}
     */
    function addOption(option,an_option,wei_option, parentid, lev) {
        if (!option) {
            layer.msg('部位不能为空');
            return false;
        }
        if (!an_option) {
            layer.msg('保养工时不能为空');
            return false;
        }
        if (!wei_option) {
            layer.msg('维修工时不能为空');
            return false;
        }

        if (!parentid) parentid = 0;
        if (!lev) lev = 0;
        var isfalse = false;
        $('.thisoption').each(function () {
            if ($(this).text() == option) {
                isfalse = true;
            }
        })
        // if (isfalse) {
        //     layer.msg('已存在该现象');
        //     return false;
        // }
        $.post('addOption?parent_id='+parentid, {
            option: option,
            an_option: an_option,
            wei_option: wei_option,
            lev: lev,
            deloption: $('#del_all_option').val()
        }, function (res) {

            console.log(res);
            layer.msg(res.message);
            if (res.code == 10000) {
                var del = $('#del_all_option').val()
                console.log('--+'+del)
                del = del.split(',');
                for (i in del) {
                    if (del[i] == res.data.id) {
                        del.splice(i, 1)
                    }
                }
                del = del.join(',');
                console.log('--'+del)
                $('#del_all_option').val(del)
                var lev_html = '';
                // if (lev > 0) {
                //     for (i = 0; i < lev; i ++) {
                //         lev_html += '&nbsp;&nbsp;&nbsp;&nbsp;|__';
                //     }
                // }
                // var html = 
                //     '<tr class="noborder option_'+res.data.id+' parent_id_'+parentid+'">\n' +
                //     '<td class="required"></td>'+
                //     '<td class="vatop rowform">\n' +
                //     ''+lev_html+' <span class="thisoption">'+option+'</span>'+
                //     ''+lev_html+' <span class="thisoption">'+an_option+'</span>'+
                //     ''+lev_html+' <span class="thisoption">'+wei_option+'</span>'+
                //      '<button type="button" data-option="'+option+'" data-id="'+res.data.id+'" onclick="deleteOption($(this))" class="btn btn-small btn-red layui-btn-danger del-option">删除</button>\n' +
                //     '<button type="button" data-option="'+option+'" onclick="updateOption($(this))" data-id="'+res.data.id+'" class="btn btn-small layui-btn-danger">修改&nbsp;</button>';

                //     if (lev != 0) {
                //         html += '&nbsp;<button type="button" data-option="'+option+'" data-lev="'+res.data.lev+'" data-id="'+res.data.id+'" id="add-answer-'+res.data.id+'" data-parentid="'+parentid+'" onclick="addAnswer($(this))" class="btn btn-small layui-btn-danger add-answer">添加原因</button>';
                //     }
                //     html += '<input type="hidden" name="option_answer['+res.data.id+']" id="option_answer_'+res.data.id+'}">\n' +
                //     '<input type="hidden" name="option_answer_del[]" id="option_answer_del_'+res.data.id+'">'
                //     '                </td>\n' +
                //     '            </tr>';
                var html = 
                    '<tr class=" option_'+res.data.id+' parent_id_'+parentid+'">\n' +
                    '<td colspan="2" class="required" >\n' +
                    ''+lev_html+' <span style="margin-left: 126px;" class="thisoption">'+option+'</span>'+
                    '&nbsp;保养工时:'+lev_html+' <span class="thisoption">'+an_option+'</span>'+
                    '&nbsp;维修工时:'+lev_html+' <span class="thisoption">'+wei_option+'</span>'+
                    '&nbsp;&nbsp;&nbsp;'+lev_html+'<button type="button" data-option="'+option+'" data-id="'+res.data.id+'" onclick="deleteOption($(this))" class="btn btn-small btn-red layui-btn-danger del-option">删除</button>\n' ;

                    // if (lev != 0) {
                    //     html += '&nbsp;<button type="button" data-option="'+option+'" data-lev="'+res.data.lev+'" data-id="'+res.data.id+'" id="add-answer-'+res.data.id+'" data-parentid="'+parentid+'" onclick="addAnswer($(this))" class="btn btn-small layui-btn-danger add-answer">添加原因</button>';
                    // }
                    html += '<input type="hidden" name="option_answer['+res.data.id+']" id="option_answer_'+res.data.id+'}">\n' +
                    '<input type="hidden" name="option_answer_del[]" id="option_answer_del_'+res.data.id+'">'
                    '                </td>\n' +
                    '            </tr>';
                if (parentid != 0) {
                    $('.option_'+parentid).after(html);
                    
                } else {
                    $('#add_parts').append(html);
                }
                $('#option').val(option);
                $('#an_option').val(an_option);
                $('#wei_option').val(wei_option);
                $('#option').val('');
                $('#an_option').val('');
                $('#wei_option').val('');
                var option_ids = $('#option-hidden').val();
                var option_arr = option_ids.split(',');
                option_arr.push(res.data.id);
                option_ids = option_arr.join(',');
                $('#option-hidden').val(option_ids);
            }
        }, 'json')
        ischild()
    }

    // TODO 删除选项
    function deleteOption(that)
    {
        var index = layer.confirm('确定要删除"'+that.attr('data-option')+'"的部位吗', {
            btn: ['确定', '取消'],
            title: false,
        }, function () {
            var id = that.attr('data-id');
            $('.option_'+id).remove();
            $('.parent_id_'+id).remove();
            var option_ids = $('#option-hidden').val();
            var option_arr = option_ids.split(',');
            for (i in option_arr) {
                if (option_arr[i] == id) {
                    option_arr.splice(i,1)
                }
            }
            var option = option_arr.join(',');
            $('#option-hidden').val(option);
            $('#del_all_option').val($('#del_all_option').val()+','+id)
            layer.msg('删除成功');
            layer.close(index)
        });
        ischild()
    }

    function getGcId1(gc_id1, select_id)
    {
        var select_od = select_id;
        $.ajax({
            type : "GET",
            contentType: "application/json;charset=UTF-8",
            url : ADMINSITEURL+"/Question/getClass.html?gc_id=" + gc_id1,
            success : function(result) {
                result = JSON.parse( result );
                var html = '';
                for(var i=0;i<result.length;i++){
                    if (result[i].gc_id == select_id) {
                        html += '<option selected value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    } else {
                        html += '<option value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    }
                }
                $('#gc_id2').html(html)
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    function getGcId2(gc_id1, select_id)
    {
        $.ajax({
            type : "GET",
            contentType: "application/json;charset=UTF-8",
            url : ADMINSITEURL+"/Question/getClass.html?gc_id=" + gc_id1,
            success : function(result) {
                result = JSON.parse( result );
                var html = '';
                for(var i=0;i<result.length;i++){
                    if (result[i].gc_id == select_id) {
                        html += '<option selected value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    } else {
                        html += '<option value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    }
                }
                $('#gc_id3').html(html)
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    function add_uploadedfile(file_data)
    {
        var newImg = '<tr id="' + file_data.file_id + '" class="tatr2"><input type="hidden" name="file_id[]" value="' + file_data.file_id + '" /><td><img width="40px" height="40px" src="' + file_data.file_path + '" /></td><td>' + file_data.file_name + '</td><td><a href="javascript:insert_editor(\'' + file_data.file_path + '\');">{$Think.lang.document_index_insert}</a> | <a href="javascript:del_file_upload(' + file_data.file_id + ');">{$Think.lang.ds_del}</a></td></tr>';
        $('#thumbnails').prepend(newImg);
    }
    function insert_editor(file_path){
        ue.execCommand('insertimage', {src:file_path});
    }
    function del_file_upload(file_id)
    {
        layer.confirm('{$Think.lang.ds_ensure_del}', {
            btn: ['{$Think.lang.ds_ok}', '{$Think.lang.ds_cancel}'],
            title: false,
        }, function () {
            $.getJSON("{:url('Protocol/ajax')}",{branch:'del_file_upload',file_id: + file_id}, function(result){
                if(result){
                    $('#' + file_id).remove();
                    layer.closeAll(); // 关闭删除图片的提示框
                }else{
                    layer.alert('{$Think.lang.document_index_del_fail}');
                }
            });
        });
    }
    
    // 获取下级分类
    $('#gc_id1').on('change',function () {
        var gc_id1 = $(this).val();
        getGcId1(gc_id1)
    })

    $('#gc_id2').on('change',function () {
        var gc_id2 = $(this).val();
        getGcId2(gc_id2)
    })


    $('.del-option').click(function () {
        deleteOption($(this));

    })
</script>
{if isset($model)}
<script>

    // 编辑初始化，处理分类选中的问题
    if ($('#gc_id1').val()) {
        var gc_id1 = '{$model->gc_id1}';
        var gc_id2 = '{$model->gc_id2}';
        var gc_id3 = '{$model->gc_id3}';
        getGcId1(gc_id1, gc_id2)
        getGcId2(gc_id2, gc_id3)
    }
</script>
{/if}
